import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_blue_plus/flutter_blue_plus.dart';
import 'package:get/get.dart';
import 'dart:math';
import '../widgets/MDropdownBtn.dart' show MDropdownBtn;
import '../states/BlueListController.dart' show BlueListController,BlueDevice;

class BluePage extends StatelessWidget {
  const BluePage({
    super.key,
  });

  @override
  Widget build(BuildContext context) {
    BlueListController blueList = Get.put(BlueListController());
    return Scaffold(
      appBar: AppBar(
        title: const Text('蓝牙'),
      ),
      body: Column(
        children: [
          const Padding(padding: EdgeInsets.only(top: 10)),
          Row(
            mainAxisAlignment: MainAxisAlignment.end,
            children: <Widget>[
              const Padding(padding: EdgeInsets.only(left: 10)),
              FilledButton(
                onPressed: _handleScan, 
                child: const Text('扫描')
              ),
              const Padding(padding: EdgeInsets.only(left: 5)),
              FilledButton(
                onPressed: _handleStopScan, 
                child: const Text('停止')
              ),
              const Padding(padding: EdgeInsets.only(left: 10)),
            ],
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.start,
            children: [
              const Padding(padding: EdgeInsets.only(left: 10)),
              const MDropdownBtn(),
              const Padding(padding: EdgeInsets.only(left: 20)),
              FilledButton(
                onPressed: _handleConnect, 
                child: const Text('连接')
              ),
            ],
          )
        ]
      ),
    );
  }
  void _listenBlueScan(results){
    final BlueListController blueList = Get.find();
    for (ScanResult r in results) {
      final remoteId=r.device.remoteId,localName=r.advertisementData.localName,rssi=r.rssi;
      if(localName.isEmpty) return;
      final idx=blueList.blues.indexWhere((val) => val.localName==localName);
      print('bluetooth[ $remoteId: "$localName" found! rssi: $rssi ]');
      if(idx==-1){
        blueList.blues.add(BlueDevice(
          localName: localName,
          rssi: rssi,
          remoteId: remoteId.toString()
        ));
      }
    }
  }
  void _handleBlueError(err){
    print(err);
  }
  void _enableBlue() async {
    if (await FlutterBluePlus.isSupported == false) {
      print("Bluetooth not supported by this device");
      return;
    }
    FlutterBluePlus.adapterState.listen((BluetoothAdapterState state) {
      print(state);
      if (state == BluetoothAdapterState.on) {
        // usually start scanning, connecting, etc
      } else {
        // show an error to the user, etc
      }
    });
    if (Platform.isAndroid) {
      await FlutterBluePlus.turnOn();
    }
  }
  Future<void> _handleScan() async {
    FlutterBluePlus.setLogLevel(LogLevel.verbose, color:false);
    _enableBlue();
    FlutterBluePlus.scanResults.listen(
      _listenBlueScan,
      onError: _handleBlueError
    );
    //_handleStopScan();
    await FlutterBluePlus.startScan();
  }

  Future<void> _handleStopScan() async {
    await FlutterBluePlus.stopScan();
  }

  Future<void> _handleConnect() async {
    final BlueListController blueList = Get.find();
    final device=BluetoothDevice.fromId(blueList.blue.remoteId);
    await device.connect();
    
    List<BluetoothService> services = await device.discoverServices();
    services.forEach((service) async {
      var characteristics = service.characteristics;
      for(BluetoothCharacteristic c in characteristics) {
        if (c.properties.read) {
          List<int> value = await c.read();
          print('read:$value');
        }
      }
    });
    
  }
}